package com.cjst.repair.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.cjst.BaseApplicaction;
import com.cjst.pojo.part.PartType;
import com.cjst.pojo.part.Parts;
import com.cjst.service.part.PartTypeService;
import com.cjst.service.part.PartsService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={BaseApplicaction.class})
public class RepairImage {
	
	@Autowired
	private PartTypeService partTypeService;
	@Autowired
	private PartsService partsService;
	
	
//	public static void main(String[] args) {
//		
//		//partTypeService
//		
//		//isConnect("http://120.77.37.252:8086/static/imgWork/avator/64914269-13eb-4c65-bf81-9f4344fe5e6b.png");
//	}
	
	
	
    @Test
	public void CheckImage_PartType() {
		WherePrams wherePrams=Method.where("delFlag", C.EQ, 0);
		List<PartType> tmp=partTypeService.list(wherePrams);
		
		tmp.forEach(one->{
			isConnect("http://120.77.37.252:8086/static/imgWork"+one.getFback());
			
		});
		
	}
    
    public void CheckImage_Parts() {
		WherePrams wherePrams=Method.where("delFlag", C.EQ, 0);
		List<Parts> tmp=partsService.list(wherePrams);
		
		tmp.forEach(one->{
			isConnect("http://120.77.37.252:8086/static/imgWork"+one.getFback1());
			
		});
		
	}
	
	
	public static int isConnect(String urlStr) {
		
		URL url=null;
		HttpURLConnection connection;
		int statusCode = -1;  
		int testCounts = 1;
		
		
		int counts = 1;
		if (urlStr == null || urlStr.length() <= 0) {
			return -1;
		}
		while (counts <= testCounts) {
			try {
				url = new URL(urlStr);
				connection = (HttpURLConnection) url.openConnection();
				statusCode = connection.getResponseCode();
				System.out.println("第" + (counts) + "/" + testCounts + "次链接，   statusCode:" + statusCode+"\t"+urlStr);
				counts++;
				// 非格式错误链接
				if (statusCode == 200) {// 可连接
					System.out.println("URL可用！");
					break;
				} else {// 不可连接
					url = null;
				}
			} catch (MalformedURLException e) {// 格式错误
				System.out.println("URL不可用，尝试连接第" + (counts) + "/" + testCounts + "次");
				url = null;
				counts++;
				continue;
			} catch (IOException e) {// io错误
				System.out.println("URL不可用，尝试连接第" + (counts) + "/" + testCounts + "次");
				url = null;
				counts++;
			}
		}
		return statusCode;
	}

}
